<?php

namespace App\Utils;

use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;
use GuzzleHttp\Handler\CurlHandler;
use GuzzleHttp\HandlerStack;
use GuzzleHttp\Middleware;
use GuzzleHttp\Psr7\Response;

class Request
{
    const int MAX_RETRIES = 3;
    public Client $client;

    public function __construct()
    {
        $handlerStack = HandlerStack::create(new  CurlHandler());
        $handlerStack->push(Middleware::retry($this->retryDecider(), $this->retryDelay()));
        $this->client = new Client(['handler' => $handlerStack]);
    }

    public function retryDecider()
    {
        return function (
            $retries,
            \GuzzleHttp\Psr7\Request $request,
            Response $response = null,
            \Exception $exception = null
        ) {
            if ($retries >= self::MAX_RETRIES) {
                return false;
            }
            if ($exception instanceof \GuzzleHttp\Exception\ConnectException) {
                echo "重试{$retries}\n";
                return true;
            }

            if ($response) {
                // 如果请求有响应，但是状态码大于等于500，继续重试(这里根据自己的业务而定)
                if ($response->getStatusCode() >= 500) {
                    echo "重试{$retries}\n";
                    return true;
                }
            }

            return false;
        };
    }

    protected function retryDelay()
    {
        return function ($numberOfRetries) {
            return 1000 * $numberOfRetries;
        };
    }
}